package cn.bonoon.kernel.web.components;

import static cn.bonoon.kernel.util.StringHelper.isNotEmpty;

import java.util.ArrayList;
import java.util.List;

import cn.bonoon.handler.impl.StandardAutoManager;
import cn.bonoon.kernel.IdGenerator;
import cn.bonoon.kernel.annotations.QueryExpression;
import cn.bonoon.kernel.descriptors.ObjectPropertyAccessor;
import cn.bonoon.kernel.descriptors.UIPropertyAccessor;
import cn.bonoon.kernel.expression.IExpressionResolver;
import cn.bonoon.kernel.expression.StandardExpressionParser;
import cn.bonoon.kernel.expression.resolver.BaseExpressionResolver;
import cn.bonoon.kernel.expression.results.RequestExpressionValue;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.annotations.AutoDataLoader;
import cn.bonoon.kernel.web.annotations.components.AsComboGrid;
import cn.bonoon.kernel.web.annotations.components.ComboGridColumn;
import cn.bonoon.kernel.web.handlers.loader.ComboAutoLoaderHandler;
import cn.bonoon.kernel.web.handlers.loader.ComboGridAutoLoaderHandler;
import cn.bonoon.kernel.web.html.UIPropertyBuilder;
import cn.bonoon.kernel.web.html.form.ComponentPropertyParser;

public class ComboGridComponent extends AbstractComboComponent {
	private final AsComboGrid com;
	public ComboGridComponent(ComponentPropertyParser property, UIPropertyAccessor accessor, AsComboGrid asComboGrid) {
		super("bupgridcombo", asComboGrid.value(), property, accessor, asComboGrid.reload());
		this.com = asComboGrid;

		for (int i = 0; i < com.columns().length; i++) {
			columns.add(new ComboColumn(com.columns()[i]));
		}
	}
	
	@Override
	protected ComboAutoLoaderHandler builderHandler(StandardAutoManager builderInitializer, AutoDataLoader autoLoader)throws Throwable{
		ComboGridAutoLoaderHandler cgalh;
		Class<?> qc = com.queryClass();
		if(null != qc){
			cgalh = new ComboGridAutoLoaderHandler(builderInitializer, qc, autoLoader, accessor.getField());
		}else{
			cgalh = new ComboGridAutoLoaderHandler(builderInitializer, autoLoader, accessor.getField());
		}
		for(ObjectPropertyAccessor property : cgalh.proterties()){
			ComboGridColumn column = property.getAnnotation(ComboGridColumn.class);
			if(null != column){
				columns.add(new ComboColumn(property, column));
			}
		}
		return cgalh;
	}
	
	private String toolbar;
	private class ComboColumn implements Comparable<ComboColumn>{
		private final ComboGridColumn column;
		private final String name;
		
		ComboColumn(ComboGridColumn column){
			this.name = column.field();
			this.column = column;
		}
		
		ComboColumn(ObjectPropertyAccessor property, ComboGridColumn column){
			this.name = property.getName();
			this.column = column;
		}
		
		@Override
		public int compareTo(ComboColumn o) {
			return o.column.ordinal() - column.ordinal();
		}
	}
	
	private List<ComboColumn> columns = new ArrayList<ComboColumn>();
	
	@Override
	protected void parser(UIPropertyBuilder builder) throws Exception {
		//处理toolbar
		if(com.searchs().length > 0){
			final StringBuilder html = builder.getInitHtml();
			final StringBuilder js = builder.getInitBlock();
			toolbar = IdGenerator.fixed();
			String btnid = IdGenerator.fixed();
				//"btn-" + componentId + "-toolbar-search";
//				txtName = "txt-search-" + componentId + "-";
			
			html.append("<div id='").append(toolbar).append("'>");
			
			js.append("jQuery('#").append(btnid).append("').click(function(){jQuery('#").append(componentId);
			js.append("').bupgridcombo('grid').bupgrid('load', {id:jQuery('#").append(builder.getEntityId()).append("').val()");
			StandardExpressionParser eParser = handler.getExpressionParser();
			IExpressionResolver expressionResolver = new BaseExpressionResolver("SOPTION"){

				@Override
				protected void _internalResolver(StandardExpressionParser seParser, String[] args) throws Exception {
					String soId = IdGenerator.fixed();
					html.append("<labal for='").append(soId).append("'>").append(args[1]).append("</label><input id='").append(soId).append("' type='text'/>");
					js.append(',').append(soId).append(":jQuery('#").append(soId).append("').val()");
					seParser.value(new RequestExpressionValue(seParser, soId));
				}
				
			};
			for(QueryExpression so : com.searchs()){
				eParser.addExpression(so, expressionResolver);
//				String soId = qp.getValue();
//				html.append("<labal for='").append(soId).append("'>").append(so.text()).append("</label><input id='").append(soId).append("' type='text'/>");
//				qp.parameter(js.append(','));
//				String soName = so.name();
//				String soId = txtName + soName;
				//js;.append(soName).append(":jQuery('#").append(soId).append("').val()");
//				addQuery(soName);
			}
			html.append("<a href='javascript:return void(null);' id='").append(btnid).append("' data-settings=\"iconClassname:'icon-search',flat:true\">查找</a></div>");
			js.append("});return false;}).bupabutton();");
		}
		super.parser(builder);
	}

	@Override
	protected void initComponentAttribute(StringBuilder js, UIPropertyBuilder builder) {
		super.initComponentAttribute(js, builder);
		if(StringHelper.isNotEmpty(toolbar)){
			js.append(",toolbar:'#").append(toolbar).append("'");
		}
		js.append(",columns:[[");
		boolean first = true;
		for(ComboColumn cc : columns){
			ComboGridColumn cgc = cc.column;
			if(first){
				first = false;
			}else{
				js.append(',');
			}
			js.append("{field:'").append(cc.name).append('\'');
			addAttribute(js, "title", cgc.title());
			if (isNotEmpty(cgc.align())){
				addAttribute(js, "align", cgc.align());
			}
			if (cgc.sortable()){
				js.append(",sortable:true");
			}
			if (cgc.width() > 0){
				addAttribute(js, "width", cgc.width());
			}
			js.append('}');
		}
		
		js.append("]]");
		if (com.rownumbers()){
			js.append(",rownumbers:true");
		}
		if (com.pagination()) {
			js.append(",pagination:true");
			if (com.pageSize() > 0){
				addAttribute(js, "pageSize", com.pageSize());
			}
			if (isNotEmpty(com.pageList())){
				addAttribute(js, "pageList", com.pageList());
			}
		}
		if (com.panelWidth() > 0){
			addAttribute(js, "panelWidth", com.panelWidth());
		}
		if (isNotEmpty(com.sortName())){
			addAttribute(js, "sortField", com.sortName());
		}
		if (isNotEmpty(com.sortOrder())){
			addAttribute(js, "sortOrder", com.sortOrder());
		}
		js.append(",fitColumns: true");
	}
	
	private void addAttribute(StringBuilder js, String name, String value) {
		js.append(',').append(name).append(":'").append(value).append('\'');
	}
	
	private void addAttribute(StringBuilder js, String name, int value) {
		js.append(',').append(name).append(":").append(value);
	}

	@Override
	protected void initInputAttribute(StringBuilder html, StringBuilder settings, UIPropertyBuilder builder) {
		super.initInputAttribute(html, settings, builder);
		settings.append(", idField:'").append(com.idField());
		settings.append("', textField:'").append(com.textField()).append("'");
//		html.append(", idField:'").append(com.idField());
//		html.append("', textField:'").append(com.textField()).append("'\"");
	}
}
